/*
 * carqueue.c
 *
 *  Created on: 2014-9-16
 *      Author: wbb
 */
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "carQue.h"

#ifdef UC_MS02

static SCarFileList  m_carfileList; //抓拍队列缓冲区
static int m_carbInit = 0;//初始化标志
static int	m_carHead;		//队列头
static int	m_carTail;		//队列尾
static int	m_carFreeSize;	//剩余可用空间大小
pthread_mutex_t m_carMutex;
//功能描述:抓拍队列初始化
//返回值：
//	=0:成功
//	－１: 失败
int carqueue_init()
{
	if(m_carbInit == 1)
		return 0;

	m_carfileList.iNum = CARLEMENT_NUM;
	m_carFreeSize = CARLEMENT_NUM-1;
	m_carHead = 0;
	m_carTail = 0;
	m_carbInit = 1;
	pthread_mutex_init(&m_carMutex, NULL);
	printf("##########################carqueue_init success\n");
	return 0;
}
//功能描述:抓拍队列资源释放
//返回值：
//	=0:成功
//	－１: 失败
int carqueue_free()
{
	if(m_carbInit == 0)
		return -1;
	
	m_carfileList.iNum = 0;
	m_carHead = 0;
	m_carTail = 0;
	m_carbInit = 0;

	pthread_mutex_destroy(&m_carMutex);
	printf("##########################carqueue_free success\n");
	return 0;
}

//返回队列可用长度
int carqueue_GetFreeSize()
{
	return m_carFreeSize;
}
//功能描述:将元素放入到队列中
//参数：
//nIndex:元素标示
//返回值：
//	=0:成功
//	－１: 失败
int carqueue_PutData(SCarFileInfo *fileInfo)
{
	pthread_mutex_lock(&m_carMutex);
	if(m_carbInit == 0)
	{
		pthread_mutex_unlock(&m_carMutex);
		printf("carqueue_PutData failed:init error\n");
		return -1;
	}
	if((m_carFreeSize<1) ||(fileInfo==NULL))
	{
		pthread_mutex_unlock(&m_carMutex);
		printf("carqueue_PutData failed:queue full\n");
		return -1;
	}
	
	//拷贝数据
	m_carfileList.fileInfo[m_carTail] = *fileInfo;

	//队尾添加数据，一直指向最后一个可用空间
	m_carTail++;
	m_carTail %= m_carfileList.iNum;
	--m_carFreeSize;

	pthread_mutex_unlock(&m_carMutex);
	return 0;
}
//功能描述:获取数据
//参数：
//allocBufInfo:有时间戳值   输出时把数据存储到结构中
//返回值：
//	=0:成功
//	－１: 失败
int carqueue_GetData(SCarFileInfo *fileInfo)
{
	pthread_mutex_lock(&m_carMutex);
	if(m_carbInit == 0)
	{
		//printf("car get data fail queue is not init\n");
		pthread_mutex_unlock(&m_carMutex);
		return -1;
	}
	//m_queNum - 1，保留1个空间，如果==m_queNUm-1，说明没有数据
	if(m_carFreeSize >= m_carfileList.iNum - 1)
	{
		pthread_mutex_unlock(&m_carMutex);
		printf("car get data failed queue is empty\n");
		return -1;
	}

	//拷贝数据
	*fileInfo = m_carfileList.fileInfo[m_carHead];

	m_carHead++;
	m_carHead %= m_carfileList.iNum;
	++m_carFreeSize;

	pthread_mutex_unlock(&m_carMutex);
	return 0;
}

#endif // UC_MS02
